import React from 'react'
import './chart.less'
import { Chart } from '@antv/g2'

class Charts extends React.Component {
	constructor(props) {
		super(props)
		this.chartRef = React.createRef()
		this.state = {
			data: [
				{ item: '正常进行中', count: 40, percent: 0.4 },
				{ item: '完成           ', count: 21, percent: 0.21 },
				{ item: '关闭           ', count: 17, percent: 0.17 },
				{ item: '挂起           ', count: 13, percent: 0.13 },
				{ item: '冻结           ', count: 9, percent: 0.09 },
			],
		}
	}

	componentDidMount() {
		this.setChart()
	}

	setChart = () => {
		const { data } = this.state
		const chart = new Chart({
			container: 'c12',
			autoFit: true,
			width: 600,
			height: 200,
		})

		chart.data(data)
		chart.scale('percent', {
			formatter: (val) => {
				val = val * 100 + '%'
				return val
			},
		})
		chart.coordinate('theta', {
			radius: 1,
			innerRadius: 0.6,
		})
		chart.tooltip({
			showTitle: false,
			showMarkers: false,
			itemTpl: `<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker" ></span>{name}: {value}</li>`,
		})
		// 辅助文本
		chart
			.interval()
			.adjust('stack')
			.position('percent')
			.color('item')
			.tooltip('item*percent', (item, percent) => {
				percent = percent * 100 + '%'
				return {
					name: item,
					value: percent,
				}
			})

		chart.annotation().text({
			position: ['50%', '50%'],
			content: '项目合计',
			style: {
				fontSize: 12,
				fill: '#8c8c8c',
				fontWeight: 300,
				textBaseline: 'bottom',
				textAlign: 'center',
			},
			offsetY: -12,
		})

		chart.annotation().text({
			position: ['50%', '50%'],
			content: 5,
			style: {
				fontSize: 18,
				fill: '#000',
				fontWeight: 500,
				textAlign: 'center',
			},
			offsetY: 10,
		})
		// NOTE: 图例
		chart.legend({
			position: 'right',
			itemHeight: 30,
			maxItemWidth: 230,
			offsetX: -50,
			itemName: {
				style: {
					fontSize: 14,
				},
			},
			itemValue: {
				alignRight: false,
				style: {
					fontSize: 14,
				},
				formatter: (text, item, index) => {
					const target = data[index]
					return `    ${target.percent * 100}%    ${target.count}`
				},
			},
		})

		chart.on('interval:click', (ev) => {
			// 获取当前点击的对象
			const res = ev.data
			if (res) {
				console.log(res.data)
			}
		})

		chart.interaction('element-active')
		chart.render()
	}

	render() {
		return (
			<div className={'chart'}>
				<div id="c12" ref={this.chartRef} />
			</div>
		)
	}
}

export default Charts
